-- bonus
-- created by dengc
-- 物品，属性奖励

return {
    -- 学习知识点
    apply = function(id, info)
        BonusM.doBonus(info, "engineering_manual_bonus");
    end,

    -- 使用道具
    useProperty = function(target, bonusId, info)
        local source = ME.user;

        -- 奖励，这里只给玩家奖励
        -- 如果奖励配置了公式，则调用公式计算
        if type(info) == "string" and
            string.startWith(info, "formula_") then
            local prefix = "formula_";
            local formulaName = string.sub(info, string.len(prefix) + 1);

            info = FormulaM.invoke(formulaName, ME.user);
        end

        local function percentAttribBonus(source, attribName, force)
            local info = 0;
            if "hp" == attribName or "mp" == attribName then
                -- 千分比恢复属性
                local maxAttrib = "max_" .. attribName;
                info = math.modf(source:queryAttrib(maxAttrib) * force / 1000);
            else
                -- 千分比增加属性
                -- 清空所有buff、debuff、special
                local baseAttrib = InterfaceM.calcBaseAttrib(source, attribName);

                info = math.modf(baseAttrib * force / 1000);
            end

            -- 最少加1点
            info = math.max(1, info);
            BonusM.doBonus({ 2, attribName, info, }, "engineering_manual_bonus");
        end

        if type(info[1]) == 'number' then
            -- 单个奖励
            -- 特殊处理千分比的属性奖励
            if info[1] == 2 and  type(info[2] == 'string')
                and string.startWith(info[2], "per_") then
                -- 一次性的千分比属性奖励
                local force = info[3];
                local attribName = string.sub(info[2], string.len("per_") + 1);
                percentAttribBonus(source, attribName, force);
            else
                BonusM.doBonus(info, "engineering_manual_bonus");
            end
        else
            -- 多个奖励
            for _, arr in pairs(info) do
                if arr[1] == 2 and  type(arr[2] == 'string')
                    and string.startWith(arr[2], "per_") then
                    -- 一次性的千分比属性奖励
                    local force = arr[3];
                    local attribName = string.sub(arr[2], string.len("per_") + 1);
                    percentAttribBonus(source, attribName, force);
                else
                    BonusM.doBonus(arr, "engineering_manual_bonus");
                end
            end
        end
    end,

    -- 二级界面描述
    desc = function(id, info)
        local temp = "";

        local baseDesc = table.deepcopy(EngineeringManualM.queryBonus(bonusId, "desc"));
        if not baseDesc or baseDesc == "" then
            return temp;
        end

        -- 如果是物品，那么显示当前已拥有数量
        if info[1] == 1 then
            temp = string.format(baseDesc, ItemM.getAmount(ME.user, info[2]));
        else
            temp = string.format(baseDesc, info[3]);
        end

        return temp .. "\n";
    end,
};
